package com.zzxx.wechat.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zzxx.wechat.entity.ArcteryxSku;
import com.zzxx.wechat.mapper.ArcteryxSkuMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArcteryxSkuDao extends ServiceImpl<ArcteryxSkuMapper, ArcteryxSku> implements IService<ArcteryxSku> {


    @Resource
    private ArcteryxSkuMapper arcteryxSkuMapper;

    public ArcteryxSku queryBySkuId(String skuId) {
        return lambdaQuery()
                .eq(ArcteryxSku::getSkuId, skuId)
                .one();
    }

    public List<ArcteryxSku> queryByLinkIds(List<Integer> linkIds) {
        return lambdaQuery()
                .in(ArcteryxSku::getLinkId, linkIds)
                .list();
    }

    public List<ArcteryxSku> queryBySkuIds(List<String> skuIds) {
        return lambdaQuery()
                .in(ArcteryxSku::getSkuId, skuIds)
                .list();
    }


    public List<ArcteryxSku> queryBySkuIds(String url, List<String> skuIds) {
        return lambdaQuery()
                .eq(ArcteryxSku::getUrl, url)
                .in(ArcteryxSku::getSkuId, skuIds)
                .list();
    }

    public int insertBatch(List<ArcteryxSku> arcteryxSkuList) {
        if (CollectionUtil.isEmpty(arcteryxSkuList)) {
            return 0;
        }
        return arcteryxSkuMapper.insertBatch(arcteryxSkuList);
    }

    public Boolean insertOrUpdateBatch(List<ArcteryxSku> arcteryxSkuList) {

        if (CollectionUtil.isEmpty(arcteryxSkuList)) {
            return true;
        }
        Map<Boolean, List<ArcteryxSku>> collect = arcteryxSkuList.stream().collect(Collectors.groupingBy(x -> x.getId() == null));

        if (CollectionUtil.isNotEmpty(collect.get(Boolean.TRUE))) {
            arcteryxSkuMapper.insertBatch(collect.get(Boolean.TRUE));
        }
        if (CollectionUtil.isNotEmpty(collect.get(Boolean.FALSE))) {
            List<ArcteryxSku> updateList = collect.get(Boolean.FALSE);
            updateBatchById(updateList);
        }
        return true;
    }

}
